package com.gopay.cashier.web.controller;

import java.text.SimpleDateFormat;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.service.gsrt.GsrtService;
import com.gopay.cashier.web.command.BankPayCallbackCommand;
import com.gopay.cashier.web.utils.CashierConfig;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.ReversalFlag;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.gsrt.GsrtAccountRechargeDao;
import com.gopay.common.cps.manager.gsrt.GsrtAccountRechargeQueryManager;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.RSAEncoderUtil;

import net.sf.json.JSONObject;

@Controller
public class CashierFrontNotifyController extends BaseController{
    @Resource(name = "gsrtAccountRechargeDao")
    private GsrtAccountRechargeDao gsrtAccountRechargeDao;

    @Resource(name = "gsrtAccountRechargeQueryManager")
    private GsrtAccountRechargeQueryManager gsrtAccountRechargeQueryManager;
    
    @Resource(name = "gsrtService")
    private GsrtService gsrtService;

    @RequestMapping("/redirect/BankPayCallback.shtml")
    public ModelAndView frontProcess(BankPayCallbackCommand command) throws WebException{

        String orderId = WebUtils.findParameterValue(getRequest(), "orderId");
        logger.info("cashier front notify start-> orderId:" + orderId);
        printRequest("CashierFrontNotifyController--frontProcess");

        String plain = sign(command);
        logger.error("sign verify plain : "+ plain);
        
        try {
            if(!RSAEncoderUtil.verify(plain, command.getSign())){
                logger.error("sign is not fit, which orderId is "+ command.getOrderId());
                return new ModelAndView("");
            }else{
                 logger.error("sign verify success, which orderId is "+ command.getOrderId());
            }
        } catch (Exception e1) {
            logger.error("verify sign error", e1);
            return new ModelAndView("");
        }
        
        ModelAndView mv = new ModelAndView("pay/notifyDelay");
        CpsGenMainOrder order =  cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,orderId);
        if(order == null)
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);

        String redirectUrl = null;
        String result = "0";
        String tranType ="101";

        //充值
        if (IntTxnCd._00500.value.equals(order.getGopayIntTxnCd()) && StringUtils.isBlank(order.getRelevanceGopayOrderId())) {
            result = (TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd() && ReversalFlag._100.value.equals(order.getReversalFlag())) ? "1" : "0";
            redirectUrl = CashierConfig.get(CashierConfig.CASHIER_INCHARGE_REDIRECT_URL) + "?success=" + result + "&orderId=" + orderId;
            mv.addObject("orderId", orderId);
        }else{
            // 如果是先登录后支付的情况（此时orgOrder不是null），要把原订单查询出来发到notify
            CpsGenMainOrder orgOrder =null;
            if(StringUtils.isNotBlank(order.getRelevanceGopayOrderId())){
                orgOrder = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,order.getRelevanceGopayOrderId());
                if(isP2P(order) || isP2P(orgOrder)){
                    tranType = "107";
                }
            }
            // eidt by huangcheng 2016年10月28日15:49:16 添加了跨境人民币汇款充值订单支付完成返回链接
            // edit by lailingyu  2017-05-11 添加了汇款拆分的支付总订单完成返回链接01735
            // start
            if (IntTxnCd._01732.value.equals(order.getGopayIntTxnCd())) {
                redirectUrl = CashierConfig.get(CashierConfig.CASHIER_REMIT_REDIRECT_URL) + "?orderId="
                        + order.getRelevanceGopayOrderId();
                mv.addObject("orderId", orderId);
            }else if(IntTxnCd._01735.value.equals(order.getGopayIntTxnCd())){ 
                redirectUrl = CashierConfig.get(CashierConfig.CASHIER_REMIT_REDIRECT_URL) + "?orderId="
                        + orderId;
                mv.addObject("orderId", orderId);
            }else if(IntTxnCd._01738.value.equals(order.getGopayIntTxnCd())){
                 //进口批量支付总订单到这，转换成进口订单号处理
                CpsGenMainOrder order01720=cpsGeneralMainOrderQueryDAO.findByRelevanceAndTxnCd(orderId,IntTxnCd._01720.value);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String tranTime = sdf.format(order.getCreatedTs());

                redirectUrl = CashierConfig.get(CashierConfig.CASHIER_BATCHPAY_REDIRECT_URL) + "?orderId=" + order01720.getMerOrderId()
                        + "&tranAmt=" + order.getMerTxnAmt() + "&tranTime=" + tranTime;
                result = (TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd()) ? "1" : "0";
                logger.info("进口批量支付总订单到这，转换成进口订单号:"+order01720);
                mv.addObject("orderId", order01720);
            }else {

                // 如果存在关联交易（原交易），应该返回原交易的orderId
                String newOrderId = (null == orgOrder) ? order.getGopayOrderId() : orgOrder.getGopayOrderId();
                redirectUrl = CashierConfig.get(CashierConfig.CASHIER_CALLBACK_REDIRECT_URL) + "?orderId=" + newOrderId
                        + "&tranType=" + tranType;
                if (null == orgOrder) {
                    result = (TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd()) ? "1" : "0";
                } else {
                    result = (TxnStaCode.TXN_STA_CD_20000.value == orgOrder.getTxnStaCd()) ? "1" : "0";
                }
                mv.addObject("orderId", newOrderId);
            }
            // eidt 跨境人民币汇款返回链接 end
        }

        //网关来源为09，G商融通notify跳转路径
        if((order.getGatewaySource().equals("09") || order.getGatewaySource().equals("10") ) 
                && order.getGopayIntTxnCd().equals("00500")
                && order.getTxnStaCd() == TxnStaCode.TXN_STA_CD_20000.value){
            try {
                gsrtService.updateGsrtRecharge(order.getGopayOrderId());
            } catch (GopayException e) {
                logger.error("更新G商融通充值业务表失败：" + e.getMessage());
                e.printStackTrace();
            }
            redirectUrl = CashierConfig.get(CashierConfig.CASHIER_CALLBACK_GSRT_URL) + "?orderId=" + orderId +"&tranType=109";
            
        }
        
        mv.addObject("redirectUrl", redirectUrl);
        mv.addObject("result", result);
        logger.info("cashier front notify end-> orderId:" + orderId+";result:"+result);
        return mv;
    }
    @RequestMapping("/redirect/BankPayCallbackSelf.shtml")
    public ModelAndView frontProcessSelf() throws WebException{
        
        String orderId = WebUtils.findParameterValue(getRequest(), "orderId");
        logger.info("cashier front notify start-> orderId:" + orderId);
        printRequest("CashierFrontNotifyController--frontProcess");
        
        ModelAndView mv = new ModelAndView("pay/notifyDelay");
        CpsGenMainOrder order =  cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,orderId);
        if(order == null)
            throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);
        
        String redirectUrl = null;
        String result = "0";
        String tranType ="101";
        
        //充值
        if (IntTxnCd._00500.value.equals(order.getGopayIntTxnCd()) && StringUtils.isBlank(order.getRelevanceGopayOrderId())) {
            result = (TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd() && ReversalFlag._100.value.equals(order.getReversalFlag())) ? "1" : "0";
            redirectUrl = CashierConfig.get(CashierConfig.CASHIER_INCHARGE_REDIRECT_URL) + "?success=" + result + "&orderId=" + orderId;
            mv.addObject("orderId", orderId);
        }else{
            // 如果是先登录后支付的情况（此时orgOrder不是null），要把原订单查询出来发到notify
            CpsGenMainOrder orgOrder =null;
            if(StringUtils.isNotBlank(order.getRelevanceGopayOrderId())){
                orgOrder = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,order.getRelevanceGopayOrderId());
                if(isP2P(order) || isP2P(orgOrder)){
                    tranType = "107";
                }
            }           
            
            // 如果存在关联交易（原交易），应该返回原交易的orderId
            String newOrderId = (null == orgOrder) ? order.getGopayOrderId() : orgOrder.getGopayOrderId();
            redirectUrl = CashierConfig.get(CashierConfig.CASHIER_CALLBACK_REDIRECT_URL) + "?orderId=" + newOrderId +"&tranType="+tranType;
            if(null == orgOrder){
                result = (TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd())?"1":"0";
            }else{
                result = (TxnStaCode.TXN_STA_CD_20000.value == orgOrder.getTxnStaCd())?"1":"0";
            }
            mv.addObject("orderId", newOrderId);
        }
        
        mv.addObject("redirectUrl", redirectUrl);
        mv.addObject("result", result);
        logger.info("cashier front notify end-> orderId:" + orderId+";result:"+result);
        return mv;
    }
    
    @RequestMapping(value="/pay/getOrderResult",method=RequestMethod.GET)
    @ResponseBody
    public String getOrderResult(String orderId){
        JSONObject json = new JSONObject();
        String result = "0";
        try {
            CpsGenMainOrder order = cpsGeneralMainOrderQueryDAO.find(CpsGenMainOrder.class,orderId);
            if(TxnStaCode.TXN_STA_CD_20000.value == order.getTxnStaCd()){
                result = "1";//成功
            }else if (order.getTxnStaCd() == TxnStaCode.TXN_STA_CD_90000.value ||
                    order.getTxnStaCd() == TxnStaCode.TXN_STA_CD_90001.value ||
                    order.getTxnStaCd() == TxnStaCode.TXN_STA_CD_90003.value ||
                    order.getTxnStaCd() == TxnStaCode.TXN_STA_CD_90101.value ||
                    order.getTxnStaCd() == TxnStaCode.TXN_STA_CD_90201.value) { //生产三期：订单状态翻译 add by zhaojt
                return "3";
            }else if((order.getTxnStaCd() >=30000 && order.getTxnStaCd()<=39999)){
                result = "3";//进行中
            }else{
                result = "2";//失败
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        logger.info("cashier front getResult -> orderId:" + orderId+";result:"+result + ",,,sessionId=" + getRequest().getSession().getId());
        json.accumulate("result", result);
        return json.toString();
    }
    public String sign(BankPayCallbackCommand orderInfo) {
        StringBuffer sign = new StringBuffer();
        String orderId = orderInfo.getOrderId();
        String amt = orderInfo.getAmt();
        String retCode = orderInfo.getRetCode();
        String retMsg = orderInfo.getRetMsg();
        String payStatus = orderInfo.getPayStatus();
        String notifyNum = orderInfo.getNotifyNum();
        String cardType = orderInfo.getCardType();
        sign.append(orderId).append("|");
        sign.append(amt).append("|");
        sign.append(retCode).append("|");
        sign.append(retMsg).append("|");
        sign.append(payStatus).append("|");
        sign.append(notifyNum).append("|");
        sign.append(cardType);
        return sign.toString();
    }
    
    
}
